package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Question;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.vo.QuestionVo;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v1/questions")
@Slf4j
public class QuestionController {
    @Autowired
    private IQuestionService questionService;
    @GetMapping("/my")
    public PageInfo<Question> my(@AuthenticationPrincipal UserDetails user, Integer pageNum){
        Integer pageSize=8;
        if (pageNum==null){
            pageNum=1;
        }
        PageInfo<Question> pageInfo=questionService.getMyQuestion(user.getUsername(),pageNum,pageSize);
        return pageInfo;
    }
    @PostMapping("")
    public String createQuestion(
            @Validated QuestionVo questionVo,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("接收到表单信息：{}",questionVo);
        if (result.hasErrors()){
            String msg =result.getFieldError().getDefaultMessage();
            return msg;
        }
            questionService.saveQuestion(questionVo,user.getUsername());
            return "ok";
    }
    @GetMapping("/teacher")
    @PreAuthorize("hasAnyAuthority('/question/answer')")
    public PageInfo<Question> teacher(@AuthenticationPrincipal UserDetails user,Integer pageNum
    ){
      Integer pageSize=8;
      if (pageNum==null)
          pageNum=1;
        PageInfo<Question> pageInfo=questionService.getTeacherQuestions(user.getUsername(),pageNum,pageSize);
        return pageInfo;
      }
}
